package com.epalmpay.service.weixin.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.collections.iterators.LoopingIterator;
import org.springframework.stereotype.Service;

import com.epalmpay.entity.Group;
import com.epalmpay.entity.Member;
import com.epalmpay.entity.MemberICCardInfo;
import com.epalmpay.entity.TradeOffline;
import com.epalmpay.enumdef.BizEnum.PaymentScene;
import com.epalmpay.enumdef.BizEnum.TransactionStatus;
import com.epalmpay.enumdef.BizEnum.TransactionType;
import com.epalmpay.util.Response;
import com.epalmpay.util.Tools;
import com.epalmpay.util.payplat.DateUtils;
import com.epalmpay.util.payplat.UtilFun;
import com.epalmpay.exception.ApplicationException;
import com.epalmpay.mapper.GroupMapper;
import com.epalmpay.mapper.MemberICCardInfoMapper;
import com.epalmpay.mapper.MemberMapper;
import com.epalmpay.mapper.TradeOfflineMapper;
import com.epalmpay.service.weixin.IWalletService;
import com.epalmpay.service.weixin.IWxApiIcCardService;
import com.epalmpay.status.Rescode;

@Service("IcCardService")
public class WxApiIcCardServiceImpl implements IWxApiIcCardService{

	@Resource
	private MemberICCardInfoMapper icCardMapper;
	
	@Resource
	private IWalletService walletService;
	
	@Resource
	private TradeOfflineMapper tradeOfflineMapper;//线下交易表
	
	@Resource
	private MemberMapper memberMapper;
	
	@Resource
	private GroupMapper groupMapper;
	
	
	@Override
	public MemberICCardInfo selectIcCardByIcCardNo(String icCardNo){
		// TODO Auto-generated method stub
		try {
			MemberICCardInfo memberICCardInfo=icCardMapper.getByICCardNo(icCardNo);
			if(memberICCardInfo!=null){
				return memberICCardInfo;
			}
		} catch (Exception e){
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 传入实体卡卡号和密码
	 * 校验实体卡是否存在，校验密码是否正确
	 */
	@Override
	public boolean selectAndCheckIcCardPwd(String icCardNo, String icCardPwd) throws ApplicationException {
		// TODO Auto-generated method stub
		MemberICCardInfo memberIcCardInfo = new MemberICCardInfo();
		memberIcCardInfo=icCardMapper.getByICCardNo(icCardNo);
		
		if(memberIcCardInfo!=null){
			if(icCardPwd.equals(memberIcCardInfo.getIccardPwd())){
				return true;//传入的实体卡密码和库中该实体卡密码一致，验证通过
			}
		}
			return false;
		
		/*if(memberIcCardInfo!=null){
			//这个号码的实体卡存在
			if(icCardPwd.equals(memberIcCardInfo.getIccardPwd())){
				return Response.getSuccess("信息正确！");
			}else{
				return Response.getError("实体卡密码错误！");
			}
		}else{
			return Response.getError("实体卡不存在！");
		}*/
	}

	@Override
	public boolean selectIcCardStatus(String icCardNo) {
		// TODO Auto-generated method stub
		 MemberICCardInfo memberIcCardInfo=icCardMapper.getByICCardNo(icCardNo);
		 Integer status=memberIcCardInfo.getStatus();
		 if(status==1||status==5){
			 return true;//表示此实体卡未激活，可以绑定
		 }
		 return false;
		/*Map<String,String> map=new HashMap<String,String>();
		if(memberIcCardInfo!=null){
			Integer status=memberIcCardInfo.getStatus();
			Long memberId=memberIcCardInfo.getMemberId();
			if(memberId!=null){
				if(status==1){
					return Response.getSuccess("status","1");//未绑定，可用
				}else if(status==2){
					return Response.getSuccess("status","2");//已绑定，不可重复绑定
				}else if(status==3){
					return Response.getSuccess("status","3");//已废弃，不可用
				}else if(status==4){
					return Response.getSuccess("status","4");//已挂失，不可用
				}
			}else{
				return Response.getSuccess("status","5");//会员编号为空，表名此实体卡从未被激活使用
			}
		}
		return Response.getSuccess("status","6");//未查到此实体卡
*/	} 
    
	
	@Override
	public Response updatePinlessIcCard(String icCardNo, String memberId) throws ApplicationException {
		try {
			MemberICCardInfo memberIcCardInfo=icCardMapper.getByICCardNo(icCardNo);
			if(memberIcCardInfo==null||memberIcCardInfo.getStatus()!=1){
				return Response.getError("实体卡已绑定或不可用！");
			}
			
			Member member = memberMapper.queryGroup(Long.parseLong(memberId));
			if(member==null){
				throw new ApplicationException(Rescode.FAIL, "会员信息不存在");
			}
			
			Group group=groupMapper.selectByPrimaryKey(member.getGroupId());
			
			
			memberIcCardInfo.setMemberId(Long.parseLong(memberId));
			memberIcCardInfo.setStatus(2);
			memberIcCardInfo.setSwitchStatus(1);
			memberIcCardInfo.setGmtPinless(new Date()); 
			icCardMapper.updateByPrimaryKeySelective(memberIcCardInfo);
			String addValue=memberIcCardInfo.getInitValue()*100+"";
			
			
			String orderId="STK"+DateUtils.getDateTimeString("yyyyMMddHHmmss", new Date())+UtilFun.createRandomNum(6);
			
			TradeOffline tradeOffline = new TradeOffline();//线下交易记录表实体
			//充值成功后，生成充值交易记录
			tradeOffline.setOrderId(orderId);//订单交易号由STK+年月日时分秒+11位随机数组成
			tradeOffline.setGroupId(memberIcCardInfo.getGroupId());
			tradeOffline.setGmtCreate(new Date());
			tradeOffline.setPayerId(Long.parseLong(memberId));//付款者ID
			tradeOffline.setPayerName(member.getName());//付款者姓名
			tradeOffline.setPayerType((byte)7);//付款者类型,7代表会员
			tradeOffline.setReceiverId(memberIcCardInfo.getGroupId().toString());//收款者ID，认为是渠道ID
			tradeOffline.setReceiverName(group.getMerchantName());//收款者姓名,认为是渠道名
			//tradeOffline.setReceiverType(receiverType);//收款者类型，
			tradeOffline.setTransactionType((byte)TransactionType.Recharge.getType());//交易类型,充值
			tradeOffline.setSubType((byte)PaymentScene.AppOut.getType());//交易子类型,app外部支付
			tradeOffline.setOrderAmount(Integer.parseInt(addValue));//订单金额
			tradeOffline.setRealAmount(Integer.parseInt(addValue));//实付金额
			tradeOffline.setPayType((byte)13);//设置支付方式为13，钱包支付
			tradeOffline.setIsWallet(true);//是否钱包交易,是
			tradeOffline.setTransactionStatus((byte)TransactionStatus.Success.getType());
			tradeOfflineMapper.insertSelective(tradeOffline);
			
			
			walletService.updateLockedAmount(memberId,"1",addValue,"0",0,orderId);
			return Response.getSuccess("绑定成功！");
		} catch (ApplicationException ae) {
			ae.setErrMsg("绑卡失败！");
			return Response.getError("绑卡失败！");
		}
	}

	
	@Override
	public MemberICCardInfo selectIcCardByMemberId(String memberId) throws ApplicationException {
		// TODO Auto-generated method stub
		MemberICCardInfo memberICCardInfo=icCardMapper.selectIcCardByMemberId(memberId);
		if(memberICCardInfo==null||memberICCardInfo.getStatus()!=2){
			return null;
		}
		
		return memberICCardInfo;
	}


	@Override
	public Response updateIcCardStatus(String icCardNo, String targetSwitchStatus, String targetStatus,String switchNo) throws ApplicationException {
		// TODO Auto-generated method stub
		try {
			MemberICCardInfo memberICCardInfo = new MemberICCardInfo();
			memberICCardInfo.setIccardNo(icCardNo);
			memberICCardInfo.setStatus(Integer.parseInt(targetStatus));
			memberICCardInfo.setSwitchStatus(Integer.parseInt(targetSwitchStatus));
			if(switchNo.equals("0")){
				//0代表是挂失，1代表取消挂失，2代表废弃
				memberICCardInfo.setGmtModified(new Date());
			}
			int a=icCardMapper.updateIcCardByIcCardNo(memberICCardInfo);
			return Response.getSuccess("操作成功！");
		} catch (NumberFormatException ae) {
			// TODO Auto-generated catch block
			ae.printStackTrace();
			return Response.getError("操作失败！");
		} 
	}

	@Override
	public Response updateIcCardPwd(String icCardNo, String newIcCardPwd) throws ApplicationException {
		// TODO Auto-generated method stub
		MemberICCardInfo memberICCardInfo = new MemberICCardInfo();
		try {
			memberICCardInfo.setIccardPwd(newIcCardPwd);
			memberICCardInfo.setIccardNo(icCardNo);
			icCardMapper.updateIcCardByIcCardNo(memberICCardInfo);
			return Response.getSuccess("密码修改成功！");
		} catch (Exception e){
			e.printStackTrace();
			return Response.getError("系统异常！");
		}
	}

	@Override
	public MemberICCardInfo selectIcCardTimeOut(Long memberId) throws ApplicationException {
		// TODO Auto-generated method stub
		if(memberId!=null){
			MemberICCardInfo memberICCardInfo = new MemberICCardInfo();
			memberICCardInfo=icCardMapper.selectIcCardByMID(memberId);
			if(memberICCardInfo!=null){
				return memberICCardInfo;
			}else{
				return null;
			}
		}else{
			return null;
		}
	}

	
}
